<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户昵称">
                <a-input allow-clear placeholder="请输入用户昵称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号码">
                <a-input allow-clear placeholder="请输入手机号码" v-model="queryParam.mobile"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="$refs.table.refresh(1)">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="$refs.table.refresh(1)">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="1"> 已启用 </a-radio-button>
          <a-radio-button value="0"> 已禁用 </a-radio-button>
        </a-radio-group>
        <div v-if="userInfo.info.username != 'admin'">
          <a-button type="primary" @click="showAddSalesman = true" icon="plus">新建</a-button>
        </div>
      </div>
      <s-table rowKey="id" size="default" :columns="columns" :data="loadData" ref="table">
        <div slot="name" slot-scope="text, record">
          <div class="name">
            <div class="pic">
              <img :src="record.avatar" alt="" />
            </div>
            <div class="info">
              <span>{{ record.name }}</span>
              <span>{{ record.mobile }}</span>
            </div>
          </div>
        </div>
        <span slot="created_at" slot-scope="text">{{ text | timeFormat }}</span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-popconfirm title="确认删除业务员吗？" @confirm="handleDelete(record)">
              <a-button type="link" size="small">删除</a-button>
            </a-popconfirm>
            <a-divider type="vertical" style="margin: 0 1px" />
            <a-dropdown>
              <a-button type="link" size="small"> 更多 <a-icon type="down" /></a-button>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a-popconfirm
                    title="确认启用业务员吗？"
                    :disabled="record.status == 1"
                    @confirm="changeStatus(record.id, 1)"
                  >
                    <a-button type="link" size="small" :disabled="record.status == 1">启用</a-button>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm
                    title="确认禁用业务员吗？"
                    :disabled="record.status == 0"
                    @confirm="changeStatus(record.id, 0)"
                  >
                    <a-button type="link" size="small" :disabled="record.status == 0">禁用</a-button>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
        <span slot="status" slot-scope="scope">
          <div class="status">
            <span :class="scope.status == 1 ? 'open' : 'close'"></span>
            <span>{{ scope.status == 1 ? '已启用' : '已禁用' }}</span>
          </div>
        </span>
      </s-table>
    </a-card>
    <!-- 新建业务员 -->
    <a-modal
      title="新建业务员"
      style="width: 500px"
      v-model="showAddSalesman"
      :afterClose="closeModal"
      :confirmLoading="btnLoading"
      :destroyOnClose="true"
      @ok="addSalesman"
    >
      <a-form-model
        ref="ruleForm"
        :model="addForm"
        :rules="addRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-model-item label="是否开启" prop="password">
          <a-radio-group v-model="addForm.status">
            <a-radio value="1"> 开启 </a-radio>
            <a-radio value="0"> 关闭 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="代理商" prop="admin_id" v-if="userInfo.info.username == 'admin'">
          <div style="display: flex">
            <a-input v-model="admin_name" placeholder="请选择代理商" disabled />
            <a-button type="primary" style="margin-left: 15px" @click="showAgency = true">选择</a-button>
          </div>
        </a-form-model-item>
        <a-form-model-item label="绑定用户" prop="saas_user_id">
          <div style="display: flex">
            <a-input v-model="saas_user_name" placeholder="请选择用户" disabled />
            <a-button type="primary" style="margin-left: 15px" @click="showUser = true">选择</a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal title="选择用户" style="width: 300px" v-model="showUser" :destroyOnClose="true" :footer="null">
      <div style="margin-bottom: 10px">
        <a-input-search placeholder="输入昵称搜索" v-model="keyword" allowClear enter-button @search="onSearch" />
      </div>
      <s-table ref="table1" rowKey="id" :columns="userColumns" :data="loadUserDataUser">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record, 'user')"> 选择 </a-button>
        </span>
      </s-table>
    </a-modal>
    <a-modal title="选择代理商" style="width: 300px" v-model="showAgency" :destroyOnClose="true" :footer="null">
      <div style="margin-bottom: 10px">
        <a-input-search placeholder="输入昵称搜索" v-model="keyword" allowClear enter-button @search="onSearch" />
      </div>
      <s-table ref="table1" rowKey="id" :columns="userColumns" :data="loadUserData">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record, 'agency')"> 选择 </a-button>
        </span>
      </s-table>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import storage from 'store'
import { STable } from '@/components'
import { getSelectUserList } from '@/api/user'
import { getList, salesmanDel, salesmanAdd, changeStatus } from '@/api/saas/salesman'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '头像',
    width: 300,
    scopedSlots: {
      customRender: 'name',
    },
  },
  {
    title: '代理账户',
    dataIndex: 'admin_name',
  },
  {
    title: '状态',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '加入时间',
    dataIndex: 'created_at',
    scopedSlots: {
      customRender: 'created_at',
    },
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

const userColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '用户信息',
    scopedSlots: { customRender: 'baseinfo' },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'SaasSalesman',
  components: {
    STable,
  },
  data() {
    return {
      showUser: false,
      showAgency: false,
      columns,
      userColumns,
      keyword: '',
      currentIndex: 0,
      loadData: (parameter) => {
        let { queryParam: data } = this
        return getList({ ...parameter, ...data })
          .then((res) => {
            return res.data
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.$refs.table.localLoading = false
          })
      },
      loadUserData: (parameter) => {
        console.log(parameter)
        return getSelectUserList({
          ...parameter,
          storeId: storage.get('storeId'),
          type: 'admin',
          keyword: this.keyword,
          scene: 'bd_agent',
        }).then((res) => {
          return res.data
        })
      },
      loadUserDataUser: (parameter) => {
        console.log(parameter)
        return getSelectUserList({
          ...parameter,
          storeId: storage.get('storeId'),
          type: 'user',
          // scene: 'user',
          keyword: this.keyword,
        }).then((res) => {
          return res.data
        })
      },
      queryParam: {
        name: '',
        mobile: '',
        status: '-1',
      },
      showAddSalesman: false,
      btnLoading: false,
      // 添加业务员的表单
      addForm: {
        status: '1',
        admin_id: '',
        saas_user_id: '',
      },
      saas_user_name: '',
      admin_name: '',
      addRules: {
        admin_id: [{ required: true, message: '请选择代理商', trigger: 'blur' }],
        saas_user_id: [{ required: true, message: '请选择用户', trigger: 'blur' }],
      },
    }
  },
  methods: {
    handleDelete(record) {
      salesmanDel({ id: record.id }).then((res) => {
        if (res.code == 0) {
          this.$refs.table.refresh()
          this.$message.success(res.msg)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 切换业务员状态
    changeStatus(id, status) {
      changeStatus({ id, status }).then((res) => {
        if (res.code == 0) {
          this.$refs.table.refresh()
          this.$message.success(res.msg)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    onSelect(item, type) {
      if (type == 'user') {
        this.addForm.saas_user_id = item.id
        this.saas_user_name = item.name
        this.showUser = false
      }
      if (type == 'agency') {
        this.addForm.admin_id = item.id
        this.admin_name = item.name
        this.showAgency = false
      }
    },
    onSearch: function () {
      this.$refs.table1.refresh(true)
    },
    // 关闭弹窗的回调
    closeModal() {
      this.addForm.status = '1'
      this.addForm.admin_id = ''
      this.addForm.saas_user_id = ''
      this.admin_name = ''
      this.saas_user_name = ''
    },
    // 添加业务员
    addSalesman() {
      this.$refs['ruleForm'].validate(async (valid) => {
        console.log(valid)
        if (valid) {
          this.btnLoading = true
          let param = {
            status: this.addForm.status,
            saas_user_id: this.addForm.saas_user_id,
          }
          if (this.userInfo.info.username == 'admin') {
            param.admin_id = this.addForm.admin_id
          }
          const res = await salesmanAdd(param)
          this.btnLoading = false
          if (res.code == 0) {
            this.showAddSalesman = false
            this.$refs.table.refresh()
            this.$message.success(res.msg)
          } else {
            this.$message.success(res.msg)
          }
        } else {
          return false
        }
      })
    },
  },
  computed: {
    userInfo() {
      return this.$store.state.user
    },
  },
  mounted() {
    console.log(this.userInfo, 'user')
  },
}
</script>

<style scoped lang="less">
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.status {
  display: flex;
  align-items: center;
  span:nth-child(1) {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
  }
  .close {
    background-color: #ccc;
  }
  .open {
    background-color: #65c817;
  }
}
</style>
